<template lang="">
    <div>
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 20px">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区 -->
        <el-card>
            <div>
                <el-alert style="margin-bottom:20px" title="注意:只允许修改第三季分类设置的相关参数" type="warning" show-icon>
                </el-alert>
                <!-- 选择商品分类区 -->

                <el-row :gutter="10">
                    <el-col :span="12">
                        <span style="margin-right:10px">选择商品的分类:</span>
                        <!-- 级联选择框 -->
                        <el-cascader v-model="cat_id" :options="paramsList"
                            :props="{expandTrigger: 'hover' ,value:'cat_id',label:'cat_name',children:'children'}"
                            @change="handleChange">
                        </el-cascader>
                    </el-col>
                </el-row>
                <!-- 页签区 -->
                <el-tabs @tab-click="tabhandleClick" v-model="activeName">
                    <el-tab-pane label="动态参数" name="many">
                        <el-button type="primary" style="margin-bottom: 20px;" size="mini" :disabled="btnChange"
                            @click="addDialogVisible=true"> 添加参数
                        </el-button>
                        <!-- 表格 -->
                        <el-table :data="manyTableData" border stripe>
                            <el-table-column type="expand">
                                <template slot-scope="{row}">
                                    <el-tag style="margin: 10px;" v-for="(i,index) in row.attr_vals" :key="i.id"
                                        closable @close="handleClose(index,row)">{{i}}
                                    </el-tag>
                                    <!-- 添加TAG标签 -->
                                    <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue"
                                        ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(row)"
                                        @blur="handleInputConfirm(row)">
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New
                                        Tag
                                    </el-button>
                                </template>


                            </el-table-column>
                            <el-table-column type="index" label="#">
                            </el-table-column>
                            <el-table-column width="width" label="参数名称" prop="attr_name">
                            </el-table-column>
                            <el-table-column width="width" label="操作">
                                <template slot-scope="{row}">
                                    <el-button type="primary" size="mini" icon="el-icon-edit"
                                        @click="editShowDialog(row.attr_id)">编辑
                                    </el-button>
                                    <el-button type="danger" size="mini" icon="el-icon-delete"
                                        @click="deleteParams(row.attr_id)">删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="静态属性" name="only">
                        <el-button type="primary" size="mini" :disabled="btnChange" style="margin-bottom: 20px;"
                            @click="addDialogVisible=true"> 添加参数
                        </el-button>
                        <!-- 静态属性表格 -->
                        <el-table :data="onlyTableData" border stripe>
                            <el-table-column type="expand">
                                <!-- 渲染TAG标签 -->
                                <template slot-scope="{row}">
                                    <el-tag type="warning" v-for="(i,index) in row.attr_vals" :key="i.id"
                                        style="margin: 10px;" closable @close="handleClose(index,row)">{{i}}</el-tag>
                                    <el-input class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue"
                                        ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(row)"
                                        @blur="handleInputConfirm(row)">
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New
                                        Tag
                                    </el-button>

                                </template>
                            </el-table-column>
                            <el-table-column type="index" label="#">
                            </el-table-column>
                            <el-table-column width="width" label="属性名称" prop="attr_name">
                            </el-table-column>
                            <el-table-column width="width" label="操作">
                                <template slot-scope="{row}">
                                    <el-button type="primary" size="mini" icon="el-icon-edit"
                                        @click="editShowDialog(row.attr_id)">编辑
                                    </el-button>
                                    <el-button type="danger" size="mini" icon="el-icon-delete"
                                        @click="deleteParams(row.attr_id)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-card>
        <!-- 添加参数的对话框 -->
        <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" width="30%" @close="addCloseDialog">
            <el-form label-width="80px" :model="addForm" :rules="addFormRules" ref="addFormRef">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改参数的对话框 -->
        <el-dialog :title="'修改'+titleText" :visible.sync="editDialogVisible" width="30%">
            <el-form label-width="80px" :model="editForm" :rules="editFormRules" ref="editFormRef">
                <el-form-item :label="titleText" prop="attrid">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParamsList">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                paramsList: [],
                cat_id: [],
                paramsId: '',
                activeName: 'many',
                manyTableData: [],
                onlyTableData: [],
                addDialogVisible: false,
                addForm: {
                    attr_id: ''
                },
                addFormRules: {
                    attr_name: [
                        { required: true, message: '请输入名称', trigger: 'blur' }
                    ]
                },
                editDialogVisible: false,
                editForm: {},
                editFormRules: {},


            }
        },
        computed: {
            btnChange() {
                if (this.cat_id.length == 3) {
                    return false
                }
                return true
            },
            // 计算标题文本
            titleText() {
                if (this.activeName === 'many') {
                    return '动态参数'
                }
                return '静态配置'
            },

        },
        created() {
            this.getParamsList()
        },
        methods: {
            async getParamsList() {
                let { data: res } = await this.$http.get('categories')

                if (res.meta.status !== 200) {
                    return this.$message.error('获取数据失败')
                }

                this.paramsList = res.data
            },

            handleChange() {
                this.handleChangeData()

            },

            tabhandleClick() {
                this.handleChangeData()

            },

            async handleChangeData() {
                if (this.cat_id.length !== 3) {
                    this.cat_id = []
                    this.manyTableData = []
                    this.onlyTableData = []

                    return
                }
                this.paramsId = this.cat_id[2]
                let { data: res } = await this.$http.get(`categories/${this.paramsId}/attributes`, { params: { sel: this.activeName } })

                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                    item.inputVisible = false
                    item.inputValue = ''
                })

                if (res.meta.status !== 200) {
                    return this.$message.error('获取参数失败')
                }
                if (this.activeName === 'many') {
                    this.manyTableData = res.data
                } else {
                    this.onlyTableData = res.data
                }
            },
            // 关闭清空信息
            addCloseDialog() {
                this.$refs.addFormRef.resetFields()
            },
            //发起添加请求
            addParams() {
                this.$refs.addFormRef.validate(async (valid) => {
                    if (!valid) {
                        return this.$message.warning(`请输入正确的${this.titleText}`)
                    }

                    let { data: res } = await this.$http.post(`categories/${this.paramsId}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
                    console.log(res);
                    if (res.meta.status !== 201) {
                        return this.$message.error('添加失败')
                    }
                    this.$message.success('添加成功')
                    this.handleChangeData()
                    this.addDialogVisible = false
                })
            },
            async editShowDialog(attr_id) {
                let { data: res } = await this.$http.get(`categories/${this.paramsId}/attributes/
                ${attr_id}`, { attr_sel: this.activeName })
                if (res.meta.status !== 200) {
                    return this.$message.error('请求失败')
                }
                this.editForm = res.data

                this.editDialogVisible = true
            },
            // 修改分类参数请求
            async editParamsList() {
                let { data: res } = await this.$http.put(`categories/${this.paramsId}/attributes/${this.editForm.attr_id}`, {
                    attr_name: this.editForm.attr_name, attr_sel: this.activeName
                })
                if (res.meta.status !== 200) {
                    return this.$message.error('修改失败')
                }
                this.$message.success('修改成功')
                this.handleChangeData()
                this.editDialogVisible = false
            },
            //删除参数的请求
            async deleteParams(id) {
                let resDleleteParams = await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if (resDleleteParams === 'cancel') {
                    return this.$message.info('已取消')
                }
                let { data: res } = await this.$http.delete(`categories/${this.paramsId}/attributes/${id}`)
                if (res.meta.status !== 200) {
                    return this.$message.error('删除失败')
                }
                this.$message.success('删除成功')
                this.handleChangeData()
            },
            // 文本失去焦点或按下回车
            async handleInputConfirm(row) {
                if (row.inputValue.trim().length === 0) {
                    row.inputValue = ''
                    row.inputVisible = false
                    return
                }
                row.attr_vals.push(row.inputValue.trim())
                row.inputValue = ''
                row.inputVisible = false
                this.saveattrVale(row)
            },
            showInput(row) {
                row.inputVisible = true
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            async saveattrVale(row) {
                let { data: res } = await this.$http.put(`categories/${this.paramsId}/attributes/${row.attr_id}`, {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                })
                if (res.meta.status !== 200) {
                    return this.$message.info('添加失败')
                }
                this.$message.success('添加成功')
            },
            //删除对应的参数
            handleClose(i, row) {
                row.attr_vals.splice(i, 1)
                this.saveattrVale(row)
            }

        },
    }
</script>
<style lang="less">
    .el-cascader-panel {
        height: 300px;
    }

    .input-new-tag {
        width: 200px;
    }
</style>